import Request from '@/js_sdk/index.js' // 下载的插件
import Constants from '@/common/constants.js'
import EncryptUtil from './encryptUtil.js';
import TokenUtil from "../common/TokenUtil";
import Secret from "./secret";
const rxAjax = new Request();

/**
 * http请求拦截器。
 */
rxAjax.interceptor.request(function (config) {
    // 根据终端分配不同的api
    let realUrl = ''
    // #ifdef H5
    realUrl = Constants.BASE_URL;
    // #endif
    // #ifdef APP-PLUS
    realUrl = Constants.APP_BASE_URL;
    // #endif
    if(!config.url.includes('http://')){
        config.url = realUrl + config.url;
    }
    let urlAry = config.url.split('?');
    if (urlAry.length > 1) {
        config.url = urlAry[0] + '?' + getQueryParams(urlAry[1]);
    }
    if (config.params) {
        for (let paramKey in config.params) {
            let paramVal = config.params[paramKey];
            config.params[paramKey] = EncryptUtil.encryptWord(paramVal, true);
        }
    }
    if (config.data) {
        if (config.header && config.header['Content-Type'] == 'application/x-www-form-urlencoded') {
            for (var key in config.data) {
                config.data[key] = EncryptUtil.encryptWord(config.data[key], true);
            }
        } else {
            let data = config.data;
            if (data instanceof Object) {
                data = JSON.stringify(data);
            }
            config.data = EncryptUtil.encryptWord(data, true);
        }
    }

    //国际化
    config.header['Accept-Language'] = getLanguage();


    //访问请求不需要添加needToken
    if (config.needToken == false) {
        return config;
    }
    // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    let token = TokenUtil.getToken();
    if (token) {
        config.header.Authorization = 'Bearer ' + token;
    }
    //添加应用appid
    let mobileAppId = uni.getStorageSync("mobileAppId");
    //当url里面有appId时候传入appID
    let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
    let curParam = routes[routes.length - 1]; //获取路由参数
    //如果地址有appId 则使用改APPID
    if (curParam.$page.options && curParam.$page.options.appId) {
        mobileAppId = curParam.$page.options.appId;
    }
    if (curParam.params && curParam.params.appId) {
        mobileAppId = curParam.params.appId
    } else if (curParam.queryAppId) {
        mobileAppId = curParam.queryAppId
    }
    if (curParam.appId) {
        mobileAppId = curParam.appId
    }
    var pages = getCurrentPages();
    if(!pages || pages.length==0){
        return;
    }
    // #ifdef H5
    let url = window.location.href;
    let queryParams = url.split('?')[1];
    if(queryParams){
        let paramArr = queryParams.split('&');
        let params = {};
        for (let i = 0; i < paramArr.length; i++) {
            let [key, value] = paramArr[i].split('=');
            params[key] = decodeURIComponent(value); // 解码值，以防URL编码
        }
        if (params && params.appId) {
            mobileAppId = params.appId
        }
    }
    // #endif
    if (mobileAppId) {
        config.header.appId = mobileAppId;
    }
    return config;
})

/**
 * http响应拦截器。
 */
rxAjax.interceptor.response(res => {
        //解码
        if(res && res.data && res.data.isEncrypt){
            let dataStr = Secret.Decrypt(res.data.data);
            try {
                let dataVal = JSON.parse(dataStr);
                res.data=dataVal;
            }catch (e){
                res.data=dataStr;
            }
        }

        let rtn = needLogin(res);
        if (rtn) {
            toLogin();
            return;
        }
        if((res.success!=undefined && !res.success) || res.code===500){
            uni.showToast({
                title: res.message, // 消息内容
                duration: 2000, // 持续时间（单位：毫秒）
                icon: 'error' // 图标类型（可选值：success/loading/none）
            });
            return ;
        }
        return res;
    },
    errRes => {
        if (needLogin(errRes)) {
            toLogin();
        }
    });

function getQueryParams(query) {
    const list = [];
    const vars = query.split('&')
    for (var i = 0; i < vars.length; i++) {
        const name = vars[i].substring(0, vars[i].indexOf('='));
        const value = vars[i].substring(vars[i].indexOf('=') + 1);
        list.push(name + '=' + EncryptUtil.encryptWord(value));
    }
    return list.join('&');
}

/**
 * 跳转到登录页面。
 */
function toLogin() {
    TokenUtil.removeToken();
    let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
    let route = routes[routes.length - 1].route //获取当前页面路由
    if (route != 'pages/RxLogin/Login') {
        if(Constants.AppType=='H5'){
            let pages = getCurrentPages()
            let currentPage = pages[pages.length - 1]
            if(currentPage){
                let curRoute = currentPage.route
                let curParams = currentPage.params
                let fromUrl=curRoute + "?" + objectToQueryString(curParams);
                if(curRoute =='pages/RxWorkbench'){
                    uni.reLaunch({
                        url: '/pages/RxLogin/Login'
                    });
                }else {
                    uni.reLaunch({
                        url: '/pages/RxLogin/Login?fromUrl=' + encodeURIComponent(JSON.stringify(fromUrl))
                    });
                }
            }else {
                uni.reLaunch({
                    url: '/pages/RxLogin/Login'
                });
            }
        }else {
            let href =  window.location.href
            uni.setStorage({key: "uniRoute", data:href});
            //跳到免密登录
            uni.reLaunch({
                url: '/pages/RxLogin/PlatformLogin'
            });
        }
    }
}

/**
 * 将对象字符串
 * name=张三&age=30
 * @param obj
 * @returns {string}
 */
function objectToQueryString(obj) {
    if(!obj){
        return "";
    }
    return Object.keys(obj)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
        .join('&');
}

/**
 * 获取国际化语言
 * @param query
 * @returns {string}
 */
function getLanguage() {
    let language = uni.getStorageSync('language');
    if (!language) {
        language = process.env.VUE_APP_LANGUAGE;
    }
    return language;
}

/**
 * 判断是否需要登录。
 * @param res
 * @returns {boolean}
 */
function needLogin(res) {
    if (res.statusCode == 401) {
        return true;
    }
    return false;
}

export default rxAjax;
